package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hxf.domain.TeacherCourse;
import com.ruoyi.hxf.domain.Type;
import com.ruoyi.hxf.mapper.RosterMapper;
import com.ruoyi.hxf.mapper.TypeMapper;
import com.ruoyi.hxf.service.ITypeService;
import com.ruoyi.system.domain.App;
import com.ruoyi.system.domain.vo.SysUserExportVo;
import com.ruoyi.system.domain.vo.SysUserImportVo;
import com.ruoyi.system.listener.SysUserImportListener;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.xxl.job.core.util.DateUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPostService postService;
    private final ISysDeptService deptService;
    private final RosterMapper rosterMapper;
    private final TypeMapper typeMapper;
    private final ITypeService iTypeService;
    /**
     * 获取用户列表
     */
//    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public TableDataInfo<SysUser> list(SysUser user, PageQuery pageQuery) {
        return userService.selectPageUserList(user, pageQuery);
    }

    /**
     * 导出用户列表
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(SysUser user, HttpServletResponse response) {
        List<SysUser> list = userService.selectUserList(user);
        List<SysUserExportVo> listVo = BeanUtil.copyToList(list, SysUserExportVo.class);
        for (int i = 0; i < list.size(); i++) {
            SysDept dept = list.get(i).getDept();
            SysUserExportVo vo = listVo.get(i);
            if (ObjectUtil.isNotEmpty(dept)) {
                vo.setDeptName(dept.getDeptName());
                vo.setLeader(dept.getLeader());
            }
        }
        ExcelUtil.exportExcel(listVo, "用户数据", SysUserExportVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @SaCheckPermission("system:user:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<SysUserImportVo> result = ExcelUtil.importExcel(file.getInputStream(), SysUserImportVo.class, new SysUserImportListener(updateSupport));
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
    }

    /**
     * 根据用户编号获取详细信息
     *
     * @param userId 用户ID
     */
//    @SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        List<SysRole> rolesOld = new ArrayList<>();
        for (SysRole role : roles) {
            if(!role.getRoleName().contains("人员")&&!role.getRoleName().contains("校长室"))
                rolesOld.add(role);
        }

        ajax.put("roles", LoginHelper.isAdmin(userId) ? rolesOld : StreamUtils.filter(rolesOld, r -> !r.isAdmin()));
//        ajax.put("roles", LoginHelper.isAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isAdmin()));
        ajax.put("posts", postService.selectPostAll());
        if (ObjectUtil.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put("user", sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            List<SysRole> rolesOlds = new ArrayList<>();
            for (SysRole role : sysUser.getRoles()) {
                if (!role.getRoleName().contains("人员") && !role.getRoleName().contains("校长室"))
                    rolesOlds.add(role);
            }
//            ajax.put("roleIds", StreamUtils.toList(sysUser.getRoles(), SysRole::getRoleId));
            ajax.put("roleIds", StreamUtils.toList(rolesOlds, SysRole::getRoleId));
        }
        return R.ok(ajax);
    }

    /**
     * 新增用户
     */
//    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysUser user) {
        user.setNickName(user.getUserName());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
            && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
            && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        user.setPassword(BCrypt.hashpw(user.getPassword()));
        int i = userService.insertUser(user);
        String id = userService.getUserIdToApp(user.getUserName());
        App app = new App();
        app.setUserId(Long.valueOf(id));
        app.setCategory(String.valueOf(1));
        userService.addApp(app);
        SysUser sysUser = userService.selectUserByUserName(user.getUserName());
        TeacherCourse teacherCourseOne = new TeacherCourse();
        teacherCourseOne.setId(Long.valueOf(1));
        teacherCourseOne.setLabel("周一");
        teacherCourseOne.setTeacherId(sysUser.getUserId());
        teacherCourseOne.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        teacherCourseOne.setCreateTime(DateUtils.getNowDate());
        rosterMapper.insertTeacherCourse(teacherCourseOne);
        TeacherCourse teacherCourseTwo = new TeacherCourse();
        teacherCourseTwo.setId(Long.valueOf(2));
        teacherCourseTwo.setLabel("周二");
        teacherCourseTwo.setTeacherId(sysUser.getUserId());
        rosterMapper.insertTeacherCourse(teacherCourseTwo);
        teacherCourseTwo.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        teacherCourseTwo.setCreateTime(DateUtils.getNowDate());
        TeacherCourse teacherCourseThree = new TeacherCourse();
        teacherCourseThree.setId(Long.valueOf(3));
        teacherCourseThree.setLabel("周三");
        teacherCourseThree.setTeacherId(sysUser.getUserId());
        teacherCourseThree.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        teacherCourseThree.setCreateTime(DateUtils.getNowDate());
        rosterMapper.insertTeacherCourse(teacherCourseThree);
        TeacherCourse teacherCourseFour = new TeacherCourse();
        teacherCourseFour.setId(Long.valueOf(4));
        teacherCourseFour.setLabel("周四");
        teacherCourseFour.setTeacherId(sysUser.getUserId());
        teacherCourseFour.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        teacherCourseFour.setCreateTime(DateUtils.getNowDate());
        rosterMapper.insertTeacherCourse(teacherCourseFour);
        TeacherCourse teacherCourseFive = new TeacherCourse();
        teacherCourseFive.setId(Long.valueOf(5));
        teacherCourseFive.setLabel("周五");
        teacherCourseFive.setTeacherId(sysUser.getUserId());
        teacherCourseFive.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        teacherCourseFive.setCreateTime(DateUtils.getNowDate());
        rosterMapper.insertTeacherCourse(teacherCourseFive);
        return toAjax(i);
    }

    /**
     * 修改用户
     */
//    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
            && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
            && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        SysUser user1 = userService.selectUserById(user.getUserId());

        String OldRoleName = rosterMapper.selectUserByIdRoleName(user.getUserId());

        int i = userService.updateUser(user);

        SysUser sysUser1 = userService.selectUserById(user.getUserId());
        String s = iTypeService.selectRoleName();
        int x = 0;
        int y = 0;

        for (SysRole role : user.getRoles()) {
            if (String.valueOf(role.getRoleId()).equals(s)) {
                x = 1;
                break;
            }
        }
        for (SysRole role : sysUser1.getRoles()) {
            boolean lll = role.getRoleName().equals("班主任");
            if (lll) {
                y = 1;
                break;
            }
        }
        if (x == 1 && y == 0) {
            String classId = iTypeService.selectFromClass(user.getUserId());
            Type typeClearLeader = new Type();
            if (classId != null) {
                typeClearLeader.setDeptId(Long.valueOf(classId));
                typeClearLeader.setClassLeader(null);
                iTypeService.updateByType(typeClearLeader);
            }
        }
        int j = 0;
        for (SysRole role : sysUser1.getRoles()) {
            boolean equals = role.getRoleName().equals(OldRoleName);
            if (equals && user.getStatus().equals(user1.getStatus()) && user1.getStatus().equals("0")) {
                j = 1;
                break;
            } else {
                boolean flag = role.getRoleName().contains("老师");
                if (flag && user.getStatus().equals("0")) {
                    SysUser sysUser = userService.selectUserByUserName(user.getUserName());
                    TeacherCourse teacherCourseOne = new TeacherCourse();
                    teacherCourseOne.setId(Long.valueOf(1));
                    teacherCourseOne.setLabel("周一");
                    teacherCourseOne.setTeacherId(sysUser.getUserId());
                    teacherCourseOne.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseOne.setCreateTime(DateUtils.getNowDate());
                    rosterMapper.insertTeacherCourse(teacherCourseOne);
                    TeacherCourse teacherCourseTwo = new TeacherCourse();
                    teacherCourseTwo.setId(Long.valueOf(2));
                    teacherCourseTwo.setLabel("周二");
                    teacherCourseTwo.setTeacherId(sysUser.getUserId());
                    teacherCourseTwo.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseTwo.setCreateTime(DateUtils.getNowDate());
                    rosterMapper.insertTeacherCourse(teacherCourseTwo);
                    teacherCourseTwo.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseTwo.setCreateTime(DateUtils.getNowDate());
                    TeacherCourse teacherCourseThree = new TeacherCourse();
                    teacherCourseThree.setId(Long.valueOf(3));
                    teacherCourseThree.setLabel("周三");
                    teacherCourseThree.setTeacherId(sysUser.getUserId());
                    teacherCourseThree.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseThree.setCreateTime(DateUtils.getNowDate());
                    rosterMapper.insertTeacherCourse(teacherCourseThree);
                    TeacherCourse teacherCourseFour = new TeacherCourse();
                    teacherCourseFour.setId(Long.valueOf(4));
                    teacherCourseFour.setLabel("周四");
                    teacherCourseFour.setTeacherId(sysUser.getUserId());
                    teacherCourseFour.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseFour.setCreateTime(DateUtils.getNowDate());
                    rosterMapper.insertTeacherCourse(teacherCourseFour);
                    TeacherCourse teacherCourseFive = new TeacherCourse();
                    teacherCourseFive.setId(Long.valueOf(5));
                    teacherCourseFive.setLabel("周五");
                    teacherCourseFive.setTeacherId(sysUser.getUserId());
                    teacherCourseFive.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                    teacherCourseFive.setCreateTime(DateUtils.getNowDate());
                    rosterMapper.insertTeacherCourse(teacherCourseFive);
                    j = 1;
                    break;
                }
            }
        }
        if (j == 0) {
            List<TeacherCourse> teacherCourses = rosterMapper.selectTeacherOne(user.getUserId());
            for (int k = 0; k < teacherCourses.size(); k++) {
                String oneC = teacherCourses.get(k).getOneC();
                if (oneC != null) {
                    Long aOneLong = typeMapper.selectCourseTeacherOneDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sOne = typeMapper.selectTeacherIdCount(aOneLong);
                    String[] splitOne = sOne.split(",");
                    StringBuffer stringBufferOne = new StringBuffer();
                    for (String s1One : splitOne) {
                        if (!s1One.equals(String.valueOf(user.getUserId()))) {
                            if (stringBufferOne.length() == 0) {
                                stringBufferOne.append(s1One);
                            } else {
                                stringBufferOne.append("," + s1One);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBufferOne.toString(), aOneLong);
                    rosterMapper.updateCourseTeacherOneT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String twoC = teacherCourses.get(k).getTwoC();
                if (twoC != null) {
                    Long aTwoLong = typeMapper.selectCourseTeacherTwoDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sTwo = typeMapper.selectTeacherIdCount(aTwoLong);
                    String[] splitsTwo = sTwo.split(",");
                    StringBuffer stringBuffersTwo = new StringBuffer();
                    for (String s1Two : splitsTwo) {
                        if (!s1Two.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersTwo.length() == 0) {
                                stringBuffersTwo.append(s1Two);
                            } else {
                                stringBuffersTwo.append("," + s1Two);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersTwo.toString(), aTwoLong);
                    rosterMapper.updateCourseTeacherTwoT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String threeC = teacherCourses.get(k).getThreeC();
                if (threeC != null) {
                    Long aThreeLong = typeMapper.selectCourseTeacherThreeDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sThree = typeMapper.selectTeacherIdCount(aThreeLong);
                    String[] splitsThree = sThree.split(",");
                    StringBuffer stringBuffersThree = new StringBuffer();
                    for (String s1Three : splitsThree) {
                        if (!s1Three.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersThree.length() == 0) {
                                stringBuffersThree.append(s1Three);
                            } else {
                                stringBuffersThree.append("," + s1Three);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersThree.toString(), aThreeLong);
                    rosterMapper.updateCourseTeacherThreeT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String fourC = teacherCourses.get(k).getFourC();
                if (fourC != null) {
                    Long aFourLong = typeMapper.selectCourseTeacherFourDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sFour = typeMapper.selectTeacherIdCount(aFourLong);
                    String[] splitsFour = sFour.split(",");
                    StringBuffer stringBuffersFour = new StringBuffer();
                    for (String s1Four : splitsFour) {
                        if (!s1Four.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersFour.length() == 0) {
                                stringBuffersFour.append(s1Four);
                            } else {
                                stringBuffersFour.append("," + s1Four);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersFour.toString(), aFourLong);
                    rosterMapper.updateCourseTeacherFourT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }
                String FiveC = teacherCourses.get(k).getFiveC();
                if (FiveC != null) {
                    Long aFiveLong = typeMapper.selectCourseTeacherFiveDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sFive = typeMapper.selectTeacherIdCount(aFiveLong);
                    String[] splitsFive = sFive.split(",");
                    StringBuffer stringBuffersFive = new StringBuffer();
                    for (String s1Five : splitsFive) {
                        if (!s1Five.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersFive.length() == 0) {
                                stringBuffersFive.append(s1Five);
                            } else {
                                stringBuffersFive.append("," + s1Five);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersFive.toString(), aFiveLong);
                    rosterMapper.updateCourseTeacherFiveT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String sixC = teacherCourses.get(k).getSixC();
                if (sixC != null) {
                    Long aSixLong = typeMapper.selectCourseTeacherSixDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sSix = typeMapper.selectTeacherIdCount(aSixLong);
                    String[] splitsSix = sSix.split(",");
                    StringBuffer stringBuffersSix = new StringBuffer();
                    for (String s1Six : splitsSix) {
                        if (!s1Six.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersSix.length() == 0) {
                                stringBuffersSix.append(s1Six);
                            } else {
                                stringBuffersSix.append("," + s1Six);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersSix.toString(), aSixLong);
                    rosterMapper.updateCourseTeacherSixT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

            }
            rosterMapper.deleteTeacherClassById(user.getUserId(), LoginHelper.getUserId(), DateUtils.getNowDate());

        }

//        Boolean One = rosterMapper.selectTeacherCourse(Long.valueOf(1), "周一", user.getUserId());
//        if(One==false){
//            TeacherCourse teacherCourseOne=new TeacherCourse();
//            teacherCourseOne.setId(Long.valueOf(1));
//            teacherCourseOne.setLabel("周一");
//            teacherCourseOne.setTeacherId(user.getUserId());
//            rosterMapper.insertTeacherCourse(teacherCourseOne);
//        }
//        Boolean Two = rosterMapper.selectTeacherCourse(Long.valueOf(2), "周二", user.getUserId());
//        if(Two==false){
//            TeacherCourse teacherCourseTwo=new TeacherCourse();
//            teacherCourseTwo.setId(Long.valueOf(2));
//            teacherCourseTwo.setLabel("周二");
//            teacherCourseTwo.setTeacherId(user.getUserId());
//            rosterMapper.insertTeacherCourse(teacherCourseTwo);
//        }
//        Boolean Three = rosterMapper.selectTeacherCourse(Long.valueOf(3), "周三", user.getUserId());
//        if(Three==false){
//            TeacherCourse teacherCourseThree=new TeacherCourse();
//            teacherCourseThree.setId(Long.valueOf(3));
//            teacherCourseThree.setLabel("周三");
//            teacherCourseThree.setTeacherId(user.getUserId());
//            rosterMapper.insertTeacherCourse(teacherCourseThree);
//        }
//        Boolean Four = rosterMapper.selectTeacherCourse(Long.valueOf(4), "周四", user.getUserId());
//        if(Four==false){
//            TeacherCourse teacherCourseFour=new TeacherCourse();
//            teacherCourseFour.setId(Long.valueOf(4));
//            teacherCourseFour.setLabel("周四");
//            teacherCourseFour.setTeacherId(user.getUserId());
//            rosterMapper.insertTeacherCourse(teacherCourseFour);
//        }
//        Boolean Five = rosterMapper.selectTeacherCourse(Long.valueOf(5), "周五", user.getUserId());
//        if(Five==false){
//            TeacherCourse teacherCourseFive=new TeacherCourse();
//            teacherCourseFive.setId(Long.valueOf(5));
//            teacherCourseFive.setLabel("周五");
//            teacherCourseFive.setTeacherId(user.getUserId());
//            rosterMapper.insertTeacherCourse(teacherCourseFive);
//        }
        return toAjax(i);
    }

    /**
     * 删除用户
     *
     * @param userIds 角色ID串
     */
//    @SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@PathVariable Long[] userIds) {
        if (ArrayUtil.contains(userIds, getUserId())) {
            return R.fail("当前用户不能删除");
        }
        for (Long userId : userIds) {

            SysUser user = userService.selectUserById(userId);
            String OldRoleName = rosterMapper.selectUserByIdRoleName(userId);
            List<TeacherCourse> teacherCourses = rosterMapper.selectTeacherOne(user.getUserId());
            for (int k = 0; k < teacherCourses.size(); k++) {
                String oneC = teacherCourses.get(k).getOneC();
                if (oneC != null) {
                    Long aOneLong = typeMapper.selectCourseTeacherOneDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sOne = typeMapper.selectTeacherIdCount(aOneLong);
                    String[] splitOne = sOne.split(",");
                    StringBuffer stringBufferOne = new StringBuffer();
                    for (String s1One : splitOne) {
                        if (!s1One.equals(String.valueOf(user.getUserId()))) {
                            if (stringBufferOne.length() == 0) {
                                stringBufferOne.append(s1One);
                            } else {
                                stringBufferOne.append("," + s1One);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBufferOne.toString(), aOneLong);
                    rosterMapper.updateCourseTeacherOneT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String twoC = teacherCourses.get(k).getTwoC();
                if (twoC != null) {
                    Long aTwoLong = typeMapper.selectCourseTeacherTwoDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sTwo = typeMapper.selectTeacherIdCount(aTwoLong);
                    String[] splitsTwo = sTwo.split(",");
                    StringBuffer stringBuffersTwo = new StringBuffer();
                    for (String s1Two : splitsTwo) {
                        if (!s1Two.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersTwo.length() == 0) {
                                stringBuffersTwo.append(s1Two);
                            } else {
                                stringBuffersTwo.append("," + s1Two);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersTwo.toString(), aTwoLong);
                    rosterMapper.updateCourseTeacherTwoT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String threeC = teacherCourses.get(k).getThreeC();
                if (threeC != null) {
                    Long aThreeLong = typeMapper.selectCourseTeacherThreeDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sThree = typeMapper.selectTeacherIdCount(aThreeLong);
                    String[] splitsThree = sThree.split(",");
                    StringBuffer stringBuffersThree = new StringBuffer();
                    for (String s1Three : splitsThree) {
                        if (!s1Three.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersThree.length() == 0) {
                                stringBuffersThree.append(s1Three);
                            } else {
                                stringBuffersThree.append("," + s1Three);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersThree.toString(), aThreeLong);
                    rosterMapper.updateCourseTeacherThreeT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String fourC = teacherCourses.get(k).getFourC();
                if (fourC != null) {
                    Long aFourLong = typeMapper.selectCourseTeacherFourDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sFour = typeMapper.selectTeacherIdCount(aFourLong);
                    String[] splitsFour = sFour.split(",");
                    StringBuffer stringBuffersFour = new StringBuffer();
                    for (String s1Four : splitsFour) {
                        if (!s1Four.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersFour.length() == 0) {
                                stringBuffersFour.append(s1Four);
                            } else {
                                stringBuffersFour.append("," + s1Four);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersFour.toString(), aFourLong);
                    rosterMapper.updateCourseTeacherFourT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }
                String FiveC = teacherCourses.get(k).getFiveC();
                if (FiveC != null) {
                    Long aFiveLong = typeMapper.selectCourseTeacherFiveDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sFive = typeMapper.selectTeacherIdCount(aFiveLong);
                    String[] splitsFive = sFive.split(",");
                    StringBuffer stringBuffersFive = new StringBuffer();
                    for (String s1Five : splitsFive) {
                        if (!s1Five.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersFive.length() == 0) {
                                stringBuffersFive.append(s1Five);
                            } else {
                                stringBuffersFive.append("," + s1Five);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersFive.toString(), aFiveLong);
                    rosterMapper.updateCourseTeacherFiveT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }

                String sixC = teacherCourses.get(k).getSixC();
                if (sixC != null) {
                    Long aSixLong = typeMapper.selectCourseTeacherSixDeptId(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                    String sSix = typeMapper.selectTeacherIdCount(aSixLong);
                    String[] splitsSix = sSix.split(",");
                    StringBuffer stringBuffersSix = new StringBuffer();
                    for (String s1Six : splitsSix) {
                        if (!s1Six.equals(String.valueOf(user.getUserId()))) {
                            if (stringBuffersSix.length() == 0) {
                                stringBuffersSix.append(s1Six);
                            } else {
                                stringBuffersSix.append("," + s1Six);
                            }
                        }
                    }
                    typeMapper.insertClassTeacher(stringBuffersSix.toString(), aSixLong);
                    rosterMapper.updateCourseTeacherSixT(user.getUserName(), OldRoleName.substring(0, OldRoleName.length() - 2), k + 1);
                }
            }
            rosterMapper.deleteTeacherClassById(userId, LoginHelper.getUserId(), DateUtils.getNowDate());
            int k = 0;
            for (SysRole role : user.getRoles()) {
                if ("班主任".equals(role.getRoleName())) {
                    k = 1;
                    break;
                }
            }
            if (k == 1) {
                String classId = iTypeService.selectFromClass(user.getUserId());
                Type typeClearLeader = new Type();
                if (classId != null) {
                    typeClearLeader.setDeptId(Long.valueOf(classId));
                    typeClearLeader.setClassLeader(null);
                    iTypeService.updateByType(typeClearLeader);
                }
            }
        }

        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
//    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
//    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     *
     * @param userId 用户ID
     */
//    @SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public R<Map<String, Object>> authRole(@PathVariable Long userId) {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        List<SysRole> rolesOlds = new ArrayList<>();
        for (SysRole role : roles) {
            if (!role.getRoleName().contains("人员") && !role.getRoleName().contains("校长室"))
                rolesOlds.add(role);
        }
//        ajax.put("roles", LoginHelper.isAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isAdmin()));
        ajax.put("roles", LoginHelper.isAdmin(userId) ? rolesOlds : StreamUtils.filter(rolesOlds, r -> !r.isAdmin()));
        return R.ok(ajax);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户Id
     * @param roleIds 角色ID串
     */
//    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public R<Void> insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return R.ok();
    }

    /**
     * 获取部门树列表
     */
//    @SaCheckPermission("system:user:list")
    @GetMapping("/deptTree")
    public R<List<Tree<Long>>> deptTree(SysDept dept) {
        return R.ok(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取学校信息
     */
    @GetMapping("/school")
    public R<List<String>> getSchool() {
        ArrayList<String> objects = new ArrayList<>();
        objects = deptService.getSchool();
        return R.ok(objects);
    }
}
